package com.company.Lock;

import java.util.concurrent.locks.ReentrantLock;

// lockInterruptibly
public class LockDemo2 {
    static ReentrantLock lock = new ReentrantLock(); // sync关键字

    public static void main(String args[]) throws Exception {
        // TODO 线程-0 抢锁
        new Thread(() -> {
            lock.lock();
            try {
                Thread.sleep(60 * 1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }).start();

        Thread.sleep(1000L); // 间隔1秒启动两个线程

        // TODO 线程-1 抢锁
        Thread th = new Thread(() -> {
            System.out.println(Thread.currentThread() + "准备抢锁 ");
            try {
                lock.lock(); // 中断 会抛出异常 -- 拿不到锁 等待
                System.out.println(Thread.currentThread() + "拿到锁");
                Thread.sleep(20_000L);  // TODO 拿到锁开始干活，模拟耗时3秒
            } catch (InterruptedException e) {
                e.printStackTrace();
            } finally {
                if (lock.isHeldByCurrentThread())
                    lock.unlock(); // 解锁
            }
        });
        th.start();

        Thread.sleep(3000L); // 3秒后，超时... 停止这个线程，让他去干其他活
        th.interrupt();;
        System.out.println("我已经通知 线程1 让它停止");

        System.in.read();
    }

}
